import { useEffect } from 'react';

export const useKeyboard = (key: KeyboardEvent['key'], callback: () => void, withBlur = true): void => {
  useEffect(() => {
    const handlePressKey = (event: KeyboardEvent) => {
      if (event.key !== key) {
        return;
      }
      callback();

      if (document.activeElement instanceof HTMLElement && withBlur) {
        document.activeElement.blur();
      }
    };

    document.addEventListener('keydown', handlePressKey);

    return () => {
      document.removeEventListener('keydown', handlePressKey);
    };
  }, [callback]);
};
